package com.tsk.base.runner;

import com.tsk.base.annotation.EnableResultServer;
import com.tsk.base.config.ResultConstant;
import com.tsk.base.result.ResultSwitch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.util.Map;
import java.util.Optional;

/**
 * @author: 黄嘉振
 * @create: 2023/4/20 8:58
 * @description:
 **/
@Component
public class ResultRunner implements ApplicationRunner {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        Map<String, Object> startBeans = applicationContext.getBeansWithAnnotation(SpringBootApplication.class);
        if (startBeans.isEmpty()) {
            return;
        }
        Map<String, Object> enableBeans = applicationContext.getBeansWithAnnotation(EnableResultServer.class);
        if (enableBeans.isEmpty()) {
            return;
        }
        Optional<Object> res = startBeans.values().stream()
                .filter(bean -> enableBeans.values().contains(bean))
                .findFirst();
        if (res.orElse(null) == null) {
            return;
        }

        String packageName = ClassUtils.getPackageName(res.get().getClass().getName());
        ResultConstant.initResultSwitch(new ResultSwitch(true, packageName));
    }
}
